package com.huiminpay.transaction.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.util.EncryptUtil;
import com.huiminpay.common.cache.util.IPUtil;
import com.huiminpay.common.cache.util.ParseURLPairUtil;
import com.huiminpay.merchant.api.AppService;
import com.huiminpay.paymentagent.api.dto.PaymentResponseDTO;
import com.huiminpay.transaction.api.dto.PayOrderDTO;
import com.huiminpay.transaction.api.service.TransactionService;
import com.huiminpay.transaction.vo.OrderConfirmVO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Controller
public class PayController {
    @Autowired
    private TransactionService transactionService;
    @Reference
    private AppService appService;

    /**
    \* 支付入口
    \* @param ticket
    \* @param type
    \* @param request
    \* @return
    */
//    @GetMapping(value = "/pay-entry/{ticket}")
//    public String payEntry(@PathVariable("ticket") String ticket) {
//        String stringBase64 = EncryptUtil.decodeUTF8StringBase64(ticket);
//        PayOrderDTO payOrderDTO = JSONObject.parseObject(stringBase64, PayOrderDTO.class);
//        String params =null;
//        try {
//            params = ParseURLPairUtil.parseURLPair(payOrderDTO);
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
//        return "forward:/pay-page?"+params;
//        //return "forward:/pay‐page";
//    }
//    @RequestMapping("/pay-page")
//    public String payPage(){
//        return "pay";
//    }

    @GetMapping(value = "/pay-entry/{ticket}")
    public String payEntry(@PathVariable("ticket") String ticket,HttpServletRequest request) {
        String stringBase64 = EncryptUtil.decodeUTF8StringBase64(ticket);
        PayOrderDTO payOrderDTO = JSONObject.parseObject(stringBase64, PayOrderDTO.class);
        payOrderDTO.setChannel("huimin_c2b");
        String params =null;
        try {
            //将对象非属性组装成参数
            params = ParseURLPairUtil.parseURLPair(payOrderDTO);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(),e);
        }
        BrowserType browserType = BrowserType.valueOfUserAgent(request.getHeader("user‐agent"));
        switch (browserType){
            case ALIPAY:
                return "forward:/pay-page?" + params;
            case WECHAT:
                return "forward:/pay-page?" + params;
            case MOBILE_BROWSER:
                return "forward:/pay-page?" + params;
            default:
                return "pay_error";
        }
    }
    @RequestMapping("/pay-page")
    public String payPage(){
        return "pay";
    }
     @ApiOperation("门店支付宝下单")
     @PostMapping("/createAliPayOrder")
    public void creatAlipayOrderForStore(OrderConfirmVO orderConfirmVO,
                                         HttpServletRequest request,
                                         HttpServletResponse response){
         PayOrderDTO payOrderDTO = new PayOrderDTO();
         BeanUtils.copyProperties(orderConfirmVO,payOrderDTO);
         Long merchantId = appService.selectAppById(payOrderDTO.getAppId()).getMerchantId();
         payOrderDTO.setMerchantId(merchantId);
         payOrderDTO.setStoreId(Long.valueOf(orderConfirmVO.getStoreId()));
         payOrderDTO.setTotalAmount(Integer.valueOf(orderConfirmVO.getTotalAmount()));
         payOrderDTO.setAppId(orderConfirmVO.getAppId());
         payOrderDTO.setClientIp(IPUtil.getIpAddr(request));

         //保存订单&//调代理服务对接支付宝
         PaymentResponseDTO<String> responseDTO = transactionService.submitOrderByApli(payOrderDTO);
         String form = responseDTO.getContent();
         response.setContentType("text/html;charset=utf-8");
         try {
             response.getWriter().write(form);
             response.getWriter().flush();
             response.getWriter().close();
         } catch (IOException e) {
             throw new RuntimeException(e);
         }
         //将支付宝响应的表单写回到客户端
    }
}